<template>
  <div class="order-list">
    <!-- 搜索栏 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option 
              v-for="item in orderStatus" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <div class="table-operations">
      <div class="left">
        <el-button type="primary" @click="handleExport">
          <el-icon><Download /></el-icon>导出订单
        </el-button>
        <el-button type="danger" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon>批量删除
        </el-button>
      </div>
      <div class="right">
        <el-button-group>
          <el-tooltip content="刷新数据" placement="top">
            <el-button @click="refreshTable">
              <el-icon><Refresh /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="密度" placement="top">
            <el-button @click="toggleDensity">
              <el-icon><Operation /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="列设置" placement="top">
            <el-button @click="toggleColumnSetting">
              <el-icon><Setting /></el-icon>
            </el-button>
          </el-tooltip>
        </el-button-group>
      </div>
    </div>

    <!-- 表格 -->
    <el-card shadow="never" class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        :size="tableSize"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="订单编号" prop="orderNo" min-width="180" show-overflow-tooltip>
          <template #default="{ row }">
            <el-button link type="primary" @click="viewOrderDetail(row)">
              {{ row.orderNo }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="商品信息" min-width="300">
          <template #default="{ row }">
            <div class="product-info">
              <el-image 
                :src="row.productImage" 
                :preview-src-list="[row.productImage]"
                class="product-image" 
              />
              <div class="product-detail">
                <div class="product-name">{{ row.productName }}</div>
                <div class="product-specs">{{ row.productSpecs }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="订单金额" prop="amount" width="120" align="right">
          <template #default="{ row }">
            <span class="amount">¥{{ row.amount.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="支付方式" prop="paymentMethod" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getPaymentTagType(row.paymentMethod)" size="small">
              {{ row.paymentMethod }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" prop="status" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="下单时间" prop="createTime" width="180" align="center" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="viewOrderDetail(row)">
              查看
            </el-button>
            <el-button 
              v-if="row.status === 'pending'" 
              link 
              type="success" 
              @click="handleShip(row)"
            >
              发货
            </el-button>
            <el-button 
              v-if="row.status === 'refunding'" 
              link 
              type="warning" 
              @click="handleRefund(row)"
            >
              退款
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { 
  Search, Refresh, Download, Delete, Operation, Setting 
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  status: '',
  dateRange: []
})

// 订单状态选项
const orderStatus = [
  { label: '待付款', value: 'unpaid' },
  { label: '待发货', value: 'pending' },
  { label: '已发货', value: 'shipped' },
  { label: '已完成', value: 'completed' },
  { label: '已取消', value: 'cancelled' },
  { label: '退款中', value: 'refunding' },
  { label: '已退款', value: 'refunded' }
]

// 表格相关
const loading = ref(false)
const tableData = ref([])
const tableSize = ref('default')
const selectedRows = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 获取订单列表
const getOrderList = async () => {
  loading.value = true
  try {
    // 这里调用接口获取数据
    // const res = await api.getOrderList({
    //   ...searchForm,
    //   page: currentPage.value,
    //   pageSize: pageSize.value
    // })
    // tableData.value = res.data.list
    // total.value = res.data.total
    
    // 模拟数据
    setTimeout(() => {
      tableData.value = Array(10).fill(null).map((_, index) => ({
        id: index + 1,
        orderNo: `ORDER${String(index + 1).padStart(8, '0')}`,
        productImage: 'https://placeholder.com/150',
        productName: '示例商品名称',
        productSpecs: '规格：默认',
        amount: Math.random() * 1000,
        paymentMethod: ['微信支付', '支付宝'][Math.floor(Math.random() * 2)],
        status: orderStatus[Math.floor(Math.random() * orderStatus.length)].value,
        createTime: new Date().toLocaleString()
      }))
      total.value = 100
      loading.value = false
    }, 500)
  } catch (error) {
    console.error(error)
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getOrderList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 表格选择
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getOrderList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getOrderList()
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    unpaid: 'info',
    pending: 'warning',
    shipped: 'primary',
    completed: 'success',
    cancelled: 'danger',
    refunding: 'warning',
    refunded: 'info'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    unpaid: '待付款',
    pending: '待发货',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消',
    refunding: '退款中',
    refunded: '已退款'
  }
  return textMap[status] || status
}

// 获取支付方式标签类型
const getPaymentTagType = (method: string) => {
  const typeMap: Record<string, string> = {
    '微信支付': 'success',
    '支付宝': 'primary'
  }
  return typeMap[method] || 'info'
}

// 查看订单详情
const viewOrderDetail = (row: any) => {
  // 实现查看详情逻辑
}

// 导出订单
const handleExport = () => {
  // 实现导出逻辑
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要删除的订单')
    return
  }
  ElMessageBox.confirm('确定要删除选中的订单吗？', '提示', {
    type: 'warning'
  }).then(() => {
    // 实现批量删除逻辑
  })
}

// 刷新表格
const refreshTable = () => {
  getOrderList()
}

// 切换表格密度
const toggleDensity = () => {
  const sizes = ['default', 'large', 'small']
  const currentIndex = sizes.indexOf(tableSize.value)
  tableSize.value = sizes[(currentIndex + 1) % sizes.length]
}

// 切换列设置
const toggleColumnSetting = () => {
  // 实现列设置逻辑
}

// 发货处理
const handleShip = (row: any) => {
  ElMessageBox.confirm(`确定要发货订单 ${row.orderNo} 吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('发货成功')
    getOrderList()
  })
}

// 退款处理
const handleRefund = (row: any) => {
  ElMessageBox.confirm(`确定要退款订单 ${row.orderNo} 吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('退款成功')
    getOrderList()
  })
}

// 删除订单
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除订单 ${row.orderNo} 吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
    getOrderList()
  })
}

// 初始化
onMounted(() => {
  getOrderList()
})
</script>

<style lang="scss" scoped>
.order-list {
  .search-card {
    margin-bottom: 16px;
    
    :deep(.el-card__body) {
      padding: 16px;
    }
  }
  
  .table-operations {
    margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .left {
      display: flex;
      gap: 8px;
    }
  }
  
  .table-card {
    :deep(.el-card__body) {
      padding: 0;
    }
  }
  
  .product-info {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .product-image {
      width: 60px;
      height: 60px;
      border-radius: 4px;
      object-fit: cover;
    }
    
    .product-detail {
      .product-name {
        font-size: 14px;
        color: var(--el-text-color-primary);
        margin-bottom: 4px;
      }
      
      .product-specs {
        font-size: 12px;
        color: var(--el-text-color-secondary);
      }
    }
  }
  
  .amount {
    font-family: monospace;
    color: #f56c6c;
    font-weight: 500;
  }
  
  .pagination-container {
    padding: 16px;
    display: flex;
    justify-content: flex-end;
  }
  
  // 优化表格样式
  :deep(.el-table) {
    border-radius: 8px 8px 0 0;
    overflow: hidden;
    
    th.el-table__cell {
      background-color: var(--el-fill-color-light);
      color: var(--el-text-color-primary);
      font-weight: 600;
    }
    
    .el-table__row {
      transition: all 0.3s;
      
      &:hover {
        background-color: var(--el-fill-color-lighter) !important;
      }
    }
  }
  
  // 优化按钮样式
  .el-button {
    &.is-link {
      padding: 4px 8px;
      height: auto;
      
      &:not(:last-child) {
        margin-right: 8px;
        padding-right: 8px;
        border-right: 1px solid var(--el-border-color-lighter);
      }
    }
  }
}
</style> 